package org.softmed.rest.server.core.http;

import java.util.ArrayList;
import java.util.List;

import org.softmed.rest.config.HttpMethod;
import org.softmed.rest.server.core.handler.HandlerProcessParameters;
import org.softmed.rest.server.core.handler.HandlerProcessor;

import com.google.inject.Inject;

public class DefaultHttpMethodProcessor implements HttpMethodProcessor,
		Cloneable {

	@Inject
	List<SpecificHttpMethodProcessor> methodProcessors;
	private SpecificHttpMethodProcessor currentHttpMethodProcessor;

	@Override
	public HttpMethodProcessor clone() {
		List<SpecificHttpMethodProcessor> temp = new ArrayList<SpecificHttpMethodProcessor>();
		for (SpecificHttpMethodProcessor specificHttpMethodProcessor : methodProcessors) {
			temp.add(specificHttpMethodProcessor.clone());
		}

		DefaultHttpMethodProcessor clone = new DefaultHttpMethodProcessor();

		clone.setMethodProcessors(temp);

		return clone;
	}

	@Override
	public void process(HttpMethod requestHttpMethod,
			HandlerProcessor instanceHandlerSolver,
			HandlerProcessParameters parameters) throws Throwable {

		currentHttpMethodProcessor = null;

		for (SpecificHttpMethodProcessor specificHttpMethodProcessor : methodProcessors) {
			if (specificHttpMethodProcessor.canProcess(requestHttpMethod)) {
				currentHttpMethodProcessor = specificHttpMethodProcessor;
				break;
			}
		}

		if (currentHttpMethodProcessor == null)
			return;

		parameters.setHttpMethod(requestHttpMethod);
		currentHttpMethodProcessor.process(requestHttpMethod,
				instanceHandlerSolver, parameters);
	}

	public List<SpecificHttpMethodProcessor> getMethodProcessors() {
		return methodProcessors;
	}

	public void setMethodProcessors(
			List<SpecificHttpMethodProcessor> methodProcessors) {
		this.methodProcessors = methodProcessors;
	}

}
